package com.sls.web.manager.game.parser;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 解压zip文件
 * 
 * @author cx
 * 
 */
public class ZipUtil {

	/**
	 * 解压zip文件
	 * 
	 * @param zipfile
	 *            zip文件
	 * @param destDir
	 *            目标文件夹
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static List<File> unZip(String zipfile, String destDir)
			throws IOException {
		destDir = destDir.endsWith(File.separator) ? destDir : destDir
				+ File.separator;
		byte b[] = new byte[1024];
		int length = 0;
		ZipFile zipFile = null;
		OutputStream outputStream = null;
		InputStream inputStream = null;
		List<File> fileList = new ArrayList<File>();
		try {
			zipFile = new ZipFile(new File(zipfile));
			Enumeration<ZipEntry> enumeration = (Enumeration<ZipEntry>) zipFile
					.entries();
			ZipEntry zipEntry = null;
			while (enumeration.hasMoreElements()) {
				zipEntry = enumeration.nextElement();
				File loadFile = new File(destDir + zipEntry.getName());
				fileList.add(loadFile);
				if (zipEntry.isDirectory()) {
					loadFile.mkdirs();
				} else {
					if (!loadFile.getParentFile().exists()) {
						loadFile.getParentFile().mkdirs();
					}
					outputStream = new FileOutputStream(loadFile);
					inputStream = zipFile.getInputStream(zipEntry);
					while ((length = inputStream.read(b)) > 0) {
						outputStream.write(b, 0, length);
						outputStream.flush();
					}
				}
				if (outputStream != null) {
					outputStream.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			}
		} catch (IOException e) {
			if (outputStream != null) {
				outputStream.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
			throw e;
		}
		return fileList;
	}

	/**
	 * @param filepath
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static List<File> readFloder(String filepath)
			throws FileNotFoundException, IOException {
		List<File> fileList = new ArrayList<File>();
		File file = new File(filepath);
		if (!file.isDirectory()) {
			fileList.add(file);
		} else if (file.isDirectory()) {
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(filepath + File.separator
						+ filelist[i]);
				if (!readfile.isDirectory()
						&& readfile.getName().endsWith(".xml")) {
					fileList.add(readfile);
				} else if (readfile.isDirectory()) {
					fileList = readFloder(filepath + File.separator
							+ filelist[i]);
				}
			}
		}
		return fileList;
	}
}
